import { KanbanService } from './../../@core/mock/kanbanSerive/kanban.service';
import { Component, ElementRef, HostListener, Renderer2, SimpleChanges } from '@angular/core';
import { WorkbenchService } from 'src/app/@core/mock/datasERVICE/workbench.service';
import * as echarts from 'echarts';
import { StorehouseService } from '../../@core/services/storehouse/storehouse.service';
import { TableWidthConfig } from 'ng-devui';
import { interval, Subscription } from 'rxjs';
@Component({
  selector: 'app-cangku-kanban',
  templateUrl: './cangku-kanban.component.html',
  styleUrls: ['./cangku-kanban.component.scss'],
})
export class CangkuKanbanComponent {
  obj = {
    Part: '',
    Type: '',
    StartTime: '',
    EndTime: '',
    PageIndex: 0,
    PageSize: 5
  };
  obj2 = {
    PartNum: '',
    PartName: '',
    PartClass: '',
    PartType: '',
    PageNumber: 0,
    PageSize: 8
  };
  tableData: any = []
  private subscription: Subscription;
  dataTableOptions = {
    columns: [
      {
        field: '单据编码',
        header: '单据编码',
        fieldType: 'text',
      },
      {
        field: '单据类型',
        header: '单据类型',
        fieldType: 'text',
      },
      {
        field: '物料',
        header: '物料',
        fieldType: 'text'
      },

      {
        field: '出/入库数量',
        header: '出/入库数量',
        fieldType: 'text'
      },
      {
        field: '出/入库时间',
        header: '出/入库时间',
        fieldType: 'text'
      },
    ]
  };//表格数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: '单据编码',
      width: '180px'
    },
    {
      field: '单据类型',
      width: ''
    },
    {
      field: '物料',
      width: ''
    },
    {
      field: '出/入库数量',
      width: ''
    },
    {
      field: '出/入库时间',
      width: '140px'
    },
  ];//表格宽度配置
  dataTableOptions2 = {
    columns: [
      {
        field: '物料',
        header: '物料',
        fieldType: 'text'
      },
      {
        field: '仓库',
        header: '仓库',
        fieldType: 'text'
      },
      {
        field: '仓位',
        header: '仓位',
        fieldType: 'text'
      },
      {
        field: '数量',
        header: '数量',
        fieldType: 'text'
      },
    ]
  };//表格数据
  tableWidthConfig2: TableWidthConfig[] = [
    {
      field: '单据编码',
      width: '155px'
    },
    {
      field: '仓库',
      width: ''
    },
    {
      field: '仓位',
      width: ''
    },
    {
      field: '数量',
      width: ''
    },

  ];
  tableData2: any = []
  warehouseData: any = {
    "totalInventory": 7510481.618,
    "totalInbound": 9123011.134,
    "totalOutbound": 1612529.516,
    "initialInboundQuantity": 112311.1313,
    "purchaseInboundQuantity": 51411.1801,
    "purchaseReturnOutboundQuantity": 16131.0111,
    "salesOutboundQuantity": 78041.112,
    "salesReturnInboundQuantity": 6131.9861,
    "jobOrderIssueOutboundQuantity": 61239.2315,
    "jobOrderReturnInboundQuantity": 5123.1041,
    "productEndInboundQuantity": 26131.1,
    "outboundDocumentQuantity": 2101,
    "inboundDocumentQuantity": 1214
  }
  chukuData: any = {}
  currentTime: Date = new Date()
  constructor(private KanbanService: KanbanService, private StorehouseService: StorehouseService, private WorkbenchService: WorkbenchService) { }
  ngOnInit(): void {
    this.KanbanService.getWarehouseData().subscribe((data: any) => {
      this.warehouseData = data;
      this.chuKuPieData(data);
      this.renderNightingaleRoseChart(data)

      console.log(this.warehouseData)
    });
    this.KanbanService.getInventoryStatistics().subscribe((data: any) => {
      const chartData = this.getRecentSixMonthsData(data);
      this.initChart(chartData);
    });
    // 首次获取数据
    this.fetchData();
    // 启动定时器进行后续数据获取
    this.startAutoRefresh();

    this.subscription = interval(2000).subscribe(() => {
      this.currentTime = new Date()
    });
  }
  ngOnDestroy(): void {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
  initChart(data: any[]): void {
    const months = data.map(item => item.month);
    const inboundAmounts = data.map(item => item.inboundAmount);
    const outboundAmounts = data.map(item => item.outboundAmount);

    const option = {
      tooltip: {
        show: true,
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      legend: {
        data: [
          { name: '入库量', textStyle: { color: '#37d6af' } },
          { name: '出库量', textStyle: { color: '#23b9ff' } }
        ],
        top: '0',
        right: '5%',
        itemWidth: 13,
        itemHeight: 13,
        icon: 'rect',
        itemStyle: {
          borderRadius: 0
        }
      },
      grid: {
        left: '0%',
        right: '5%',
        bottom: '8%',
        top: '16%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: months,
        axisLabel: {
          formatter: function (value: string) {
            const parts = value.split('年');
            return `${parts[0]}年\n${parts[1]}`;
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '数量',
        axisLine: {
          show: true,
        },
        axisLabel: {
          formatter: '{value} '
        },
      },
      series: [
        {
          data: inboundAmounts,
          name: "入库量",
          barWidth: '20%',
          type: 'bar',
          itemStyle: {
            color: 'rgba(61, 252, 205, 0.7)',
            borderColor: '#37d6af',
            borderWidth: 2,
          },
          label: {
            show: true,
            position: 'top',
            formatter: function (params: any) {
              return `${params.value} `;
            },
            textStyle: {
              color: '#37d6af',
            }
          },
          barGap: '30%',
          barCategoryGap: '50%'
        },
        {
          data: outboundAmounts,
          name: "出库量",
          barWidth: '20%',
          type: 'bar',
          itemStyle: {
            color: 'rgba(35, 185, 255, 0.7)',
            borderColor: '#23b9ff',
            borderWidth: 2,
          },
          label: {
            show: true,
            position: 'top',
            formatter: function (params: any) {
              return `${params.value}`;
            },
            textStyle: {
              color: '#23b9ff',
            }
          },
          barGap: '70%',
        }
      ]
    };
    const myChart = echarts.init(document.getElementById('inAndOutData') as HTMLElement);
    myChart.resize();
    window.addEventListener('resize', function () {
      myChart.resize();
    });
    myChart.setOption(option);
  }
  chuKuPieData(data: any): void {
    const totalOutbound = data.salesOutboundQuantity + data.purchaseReturnOutboundQuantity + data.jobOrderIssueOutboundQuantity;
    const pieData = [
      { name: '销售出库', value: data.salesOutboundQuantity, itemStyle: { color: '#4adeca' } },
      { name: '采购退货', value: data.purchaseReturnOutboundQuantity, itemStyle: { color: '#38cafb' } },
      { name: '生产领料', value: data.jobOrderIssueOutboundQuantity, itemStyle: { color: '#488cf7' } },
    ];

    // 计算比例并赋值给 chukuData
    this.chukuData = {
      salesOutboundPercentage: (data.salesOutboundQuantity / totalOutbound * 100).toFixed(2),
      purchaseReturnPercentage: (data.purchaseReturnOutboundQuantity / totalOutbound * 100).toFixed(2),
      jobOrderIssuePercentage: (data.jobOrderIssueOutboundQuantity / totalOutbound * 100).toFixed(2)
    };

    const option = {
      tooltip: {
        trigger: 'item',
        formatter: function (params: any) {
          return `${params.seriesName}<br/><span style="display:inline-block;width:10px;height:10px;border-radius:50%;background-color:${params.color};margin-right:5px;"></span>${params.name}: ${params.value} (${params.percent.toFixed(2)}%)`;
        }
      },
      legend: {
        orient: 'horizontal',
        left: 'center',
        data: [
          { name: '销售出库', textStyle: { color: '#4adeca' } },
          { name: '采购退货', textStyle: { color: '#38cafb' } },
          { name: '生产领料', textStyle: { color: '#488cf7' } }
        ]
      },
      series: [
        {
          name: '出库类型',
          type: 'pie',
          radius: '50%',
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            show: true,
            formatter: function (params: any) {
              if (params.name === '销售出库') {
                return `{a|${params.name}: ${params.value}}`;
              } else if (params.name === '采购退货') {
                return `{b|${params.name}: ${params.value}}`;
              } else {
                return `{c|${params.name}: ${params.value}}`;
              }
            },
            rich: {
              a: {
                color: '#4adeca',
                fontSize: 14
              },
              b: {
                color: '#38cafb',
                fontSize: 14
              },
              c: {
                color: '#488cf7',
                fontSize: 14
              }
            }
          },
        }
      ]
    };
    const myChart = echarts.init(document.getElementById('chuKuPieData') as HTMLElement);
    myChart.resize();
    window.addEventListener('resize', function () {
      myChart.resize();
    });
    myChart.setOption(option);
  }
  rukuData: any = {};

  renderNightingaleRoseChart(data: any): void {
      const totalInbound = data.initialInboundQuantity + data.purchaseInboundQuantity + data.salesReturnInboundQuantity + data.jobOrderReturnInboundQuantity + data.productEndInboundQuantity;
      const roseData = [
        { value: data.initialInboundQuantity, name: '初期入库', itemStyle: { color: '#0868d9' } },
        { value: data.purchaseInboundQuantity, name: '采购入库', itemStyle: { color: '#4caff9' } },
        { value: data.salesReturnInboundQuantity, name: '销售退货', itemStyle: { color: '#38cafb' } },
        { value: data.jobOrderReturnInboundQuantity, name: '生产退料', itemStyle: { color: '#488cf7' } },
        { value: data.productEndInboundQuantity, name: '生产入库', itemStyle: { color: '#4adfcb' } }
      ].sort((a, b) => b.value - a.value); // 按照 value 的大小降序排列

      // 计算比例并赋值给 rukuData
      this.rukuData = {
        initialInboundPercentage: (data.initialInboundQuantity / totalInbound * 100).toFixed(2),
        purchaseInboundPercentage: (data.purchaseInboundQuantity / totalInbound * 100).toFixed(2),
        salesReturnInboundPercentage: (data.salesReturnInboundQuantity / totalInbound * 100).toFixed(2),
        jobOrderReturnInboundPercentage: (data.jobOrderReturnInboundQuantity / totalInbound * 100).toFixed(2),
        productEndInboundPercentage: (data.productEndInboundQuantity / totalInbound * 100).toFixed(2)
      };

      const rich = {};
      roseData.forEach((item, index) => {
        rich[`label${index}`] = {
          color: item.itemStyle.color
        };
      });

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            // 使用 HTML 代码自定义 tooltip 内容
            return `
              <div style="display: flex; align-items: center;">
                <span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background-color: ${params.color}; margin-right: 5px;"></span>
                ${params.seriesName} <br/>${params.name} : ${params.value} (${params.percent}%)
              </div>
            `;
          },
        },
        grid: {
          left: '0%',
          right: '5%',
          bottom: '12%',
          top: '0%',
          containLabel: true
        },
        series: [
          {
            name: '入库类型',
            type: 'pie',
            radius: ['17%', '80%'],
            center: ['50%', '46%'],
            roseType: 'area',
            itemStyle: {
              borderRadius: 0
            },
            label: {
              formatter: (params) => {
                const index = roseData.findIndex(item => item.name === params.name);
                return `{label${index}|${params.name}\n${params.value} (${params.percent}%)}`
              },
              rich: {
                ...rich,
                ...Object.keys(rich).reduce((acc, key) => {
                  acc[key] = {
                    ...rich[key],
                    fontSize: '14px', // 调整字体大小
                    lineHeight: 18 // 调整行间距
                  };
                  return acc;
                }, {})
              }
            },
            labelLine: {
              length: 5, // 调整标签线条的第一段长度
              length2: 5, // 调整标签线条的第二段长度
              smooth: true // 使标签线条平滑
            },
            data: roseData,
            sort: 'ascending'
          }
        ]
      };

      const chartDom = document.getElementById('chuku') as HTMLElement;
      const myChart = echarts.init(chartDom);
      myChart.setOption(option);
      myChart.resize();
      window.addEventListener('resize', () => myChart.resize());
  }
  fetchData(): void {
    this.obj.PageIndex++;
    this.obj2.PageNumber++;
    this.StorehouseService.GetIssuedPositionInventory(this.obj2).subscribe((data: any) => {
      this.tableData2 = data.items;
      if (data.items.length < 8) {
        this.obj2.PageNumber = 1;
      }
    });
    this.StorehouseService.GetInventoryDetailsPaged(this.obj).subscribe((data: any) => {
      this.tableData = data.items;
      if (data.items.length < 5) {
        this.obj.PageIndex = 1;
      }
    });
  }
  startAutoRefresh(): void {
    this.subscription = interval(2000).subscribe(() => {
      this.fetchData();
    });
  }
  getRecentSixMonthsData(data: any[]): any[] {
    const now = new Date();
    const currentMonth = `${now.getFullYear()}年${now.getMonth() + 1}月`;
    const currentIndex = data.findIndex(item => item.month === currentMonth);
    if (currentIndex === -1) {
      throw new Error("Current month not found in data");
    }
    const startIndex = Math.max(0, currentIndex - 5);
    return data.slice(startIndex, currentIndex + 1);
  }

}
